//
//  SpinMutex.hpp
//  DemoV2
//
//  Created by 董一龙 on 2022/8/8.
//

#ifndef SpinMutex_hpp
#define SpinMutex_hpp

#include <cstdint>
#include <atomic>
#include <thread>

/**
* @class SpinMutex
* @brief 简单适应策略的自旋锁
* @author yilongdong
* @note
* 如果自旋次数大于max_times就yield
*/
class SpinMutex {
    std::atomic_flag flag = ATOMIC_FLAG_INIT;
    thread_local static int32_t times; ///< 自旋计数
    static constexpr int32_t threshold = 20; ///< 自旋阈值
public:
    SpinMutex() = default;
    ~SpinMutex() = default;
    SpinMutex(SpinMutex const&) = delete;
    SpinMutex(SpinMutex &&) = delete;
    SpinMutex& operator=(SpinMutex const&) = delete;
    SpinMutex& operator=(SpinMutex &&) = delete;
    void lock();
    void unlock();
};
#endif /* SpinMutex_hpp */
